/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef IMAGE_KNIFE_C_MEMORY_CACHE_INTERCEPTOR_OH_H
#define IMAGE_KNIFE_C_MEMORY_CACHE_INTERCEPTOR_OH_H

#include "interceptor.h"
#include "imageknife_request.h"
#include "memory_cache.h"
#include "imageknife_internal.h"
#include "imageknife_data_napi.h"
#include "hitrace/trace.h"
#include <sstream>

namespace ImageKnifePro {
class MemoryCacheInterceptorDefault : public MemoryCacheInterceptor {
public:
    MemoryCacheInterceptorDefault()
    {
        name = "Default MemoryCacheInterceptor";
    }

    bool Resolve(std::shared_ptr<ImageKnifeTask> task) override
    {
        bool result = false;
        const int traceId = 2;
        if (task->cacheTask.type == CacheTaskType::WRITE) {
            OH_HiTrace_StartAsyncTrace("MemoryCacheInterceptor WRITE", traceId);
            result = Write(task);
            OH_HiTrace_FinishAsyncTrace("MemoryCacheInterceptor WRITE", traceId);
        } else if (task->cacheTask.type == CacheTaskType::READ) {
            OH_HiTrace_StartAsyncTrace("MemoryCacheInterceptor READ", traceId);
            result = Read(task);
            OH_HiTrace_FinishAsyncTrace("MemoryCacheInterceptor READ", traceId);
        }

        return result;
    }

private:
    bool Read(std::shared_ptr<ImageKnifeTask> task)
    {
        if (MemoryCache::GetInstance()->Contains(task->cacheTask.cacheKey)) {
            task->product.imageDataCache = MemoryCache::GetInstance()->Get(task->cacheTask.cacheKey);
            if (task->product.imageDataCache == nullptr) {
                task->EchoError("Empty ImageData");
                return false;
            }
            return true;
        }

        return false;
    }

    bool Write(std::shared_ptr<ImageKnifeTask> task)
    {
        if (task->product.imageDataCache == nullptr) {
            task->EchoError("Try to Cache Empty ImageData");
            return false;
        }

        if (!MemoryCache::GetInstance()->Contains(task->cacheTask.cacheKey)) {
            MemoryCache::GetInstance()->Put(task->cacheTask.cacheKey, task->product.imageDataCache);
        }
        return true;
    }
};

};

#endif // IMAGE_KNIFE_C_MEMORY_CACHE_INTERCEPTOR_OH_H
